package makabakaquestionnaire.zutsoftware.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import makabakaquestionnaire.zutsoftware.constant.Result;
import makabakaquestionnaire.zutsoftware.entity.ProjectSetting;
import makabakaquestionnaire.zutsoftware.entity.UserProject;
import makabakaquestionnaire.zutsoftware.enums.ProjectStatusEnum;
import makabakaquestionnaire.zutsoftware.mapper.ProjectSettingMapper;
import makabakaquestionnaire.zutsoftware.service.ProjectSettingService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Date;

@Service
public class ProjectSettingServiceImpl implements ProjectSettingService {
    ProjectSettingMapper projectSettingMapper;

    UserProjectServiceImpl userProjectService;
    @Autowired
    public void setUserProjectService(UserProjectServiceImpl userProjectService) {
        this.userProjectService = userProjectService;
    }

    @Autowired
    public void setProjectSettingMapper(ProjectSettingMapper projectSettingMapper) {
        this.projectSettingMapper = projectSettingMapper;
    }

    @Override
    public ProjectSetting querySettingByProKey(String ProKey) {
        return projectSettingMapper.querySettingByProKey(ProKey);
    }

    @Override
    public Boolean saveProjectSetting(ProjectSetting projectSetting) {
       int n=  projectSettingMapper.saveProjectSetting(projectSetting);
         if (n!=1){
             return false;
         }else {
             return true;
         }
    }

    @Override
    public Boolean updateProjectSetting(ProjectSetting projectSetting) {
        int n=projectSettingMapper.updateProjectSetting(projectSetting);
        if (n!=1){
            return false;
        }else {
            return true;
        }
    }

    @Override
    public Boolean deleteProjectSetting(String ProKey) {
        return null;
    }

    @Override
    public Result getUserProjectSettingStatus(String projectKey, String requestIp) {
        UserProject userProject=userProjectService.queryProjectByProKey(projectKey);
        if (ObjectUtil.isEmpty(userProject)||userProject.getStatus()!= ProjectStatusEnum.RELEASE.getValue()){
            return Result.success(null,"问卷未发布或者问卷为空，无法填写");
        }
        ProjectSetting projectSetting=this.querySettingByProKey(projectKey);
        if (ObjectUtil.isNotEmpty(projectSetting)){
          Date beginTime=  projectSetting.getCollectionBeginTime();
          Date endTime=projectSetting.getCollectionEndTime();
          String now = DateUtil.now();
          Date date=DateUtil.parse(now);   //转为date格式
           if (date.before(beginTime)){
               return Result.success(null,projectSetting.getNotEnabledTipsText());
           }else if (date.after(endTime)){
               return Result.success(null,projectSetting.getStoppedTipsText());
           }
        }
        return Result.success(projectSetting);
    }
}
